<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card class="box-card">
        <!-- 搜索与添加区域 -->
        <el-row :gutter="20">
            <el-col :span="7">
                <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUserList" >
                  <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
               </el-input>
            </el-col>
            <el-col :span="4">
                <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
            </el-col>
        </el-row>
        <!-- 用户列表区域 -->
        <el-table :data="userList" stripe>
            <el-table-column  label="#" type="index"></el-table-column>
            <el-table-column label="姓名" prop="username"></el-table-column>
            <el-table-column label="邮箱" prop="email"></el-table-column>
            <el-table-column label="电话" prop="mobile"></el-table-column>
            <el-table-column label="角色" prop="role_name"></el-table-column>
            <el-table-column label="状态">
                <template slot-scope="scope">
                    <el-switch
                    v-model="scope.row.mg_state"
                    @change="userStateChange(scope.row)">
                    </el-switch>
                </template>
            </el-table-column>
            <el-table-column label="操作" >
                <template slot-scope="scope">
                    <el-button type="primary" icon="el-icon-edit" @click="showEditDialog(scope.row.id)" circle></el-button>
                    <el-button type="danger" icon="el-icon-delete" @click="deletInfo(scope.row.id)" circle></el-button>
                    <el-tooltip class="item" effect="dark" content="分配角色" placement="top" :enterable="false">
                    <el-button type="warning" icon="el-icon-setting"  @click="showSetRole(scope.row)" circle></el-button>
                    </el-tooltip>
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页区域 -->
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="queryInfo.pagenum"
            :page-sizes="[1, 2, 5, 10]"
            :page-size="queryInfo.pagesize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
        </el-pagination>
        <!-- 添加用户的对话框 -->
        <el-dialog title="添加用户" :visible.sync="addDialogVisible" width="50%" @close="addDialogClosed">
           <!-- 内容主体区域 -->
          <el-form :model="addUserForm" status-icon :rules="AddUserRules" ref="AddUsersFormRef" label-width="70px" class="add_user_form">
            <el-form-item label="用户名" prop="username">
                <el-input v-model="addUserForm.username"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password">
                <el-input v-model="addUserForm.password"></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
                <el-input v-model="addUserForm.email"></el-input>
            </el-form-item>
            <el-form-item label="手机" prop="mobile">
                <el-input v-model="addUserForm.mobile"></el-input>
            </el-form-item>
            </el-form>
          <span slot="footer" class="dialog-footer">
            <!-- 底部按钮区域 -->
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addUser">确 定</el-button>
          </span>
        </el-dialog>
        <!-- 修改用户的对话框 -->
        <el-dialog
          title="修改用户"
          :visible.sync="showEditDialogVisible"
          width="50%"
          @close="editDialogClosed"
          >
          <el-form :model="userInfo" status-icon :rules="AddUserRules" ref="EidtUsersFormRef" label-width="70px" class="add_user_form">
            <el-form-item label="用户名">
                <el-input v-model="userInfo.username" :disabled="true" ></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
                <el-input v-model="userInfo.email"></el-input>
            </el-form-item>
            <el-form-item label="手机" prop="mobile">
                <el-input v-model="userInfo.mobile"></el-input>
            </el-form-item>
            </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="showEditDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="editUser">确 定</el-button>
          </span>
        </el-dialog>
        <!-- 分配角色对话框 -->
        <el-dialog title="分配角色" :visible.sync="showSetRoleVisible" width="50%" @close="setRoleDialogClosed">
          <div>
            <p>当前用户：{{setUserInfo.username}}</p>
            <p>用户角色：{{setUserInfo.role_name}}</p>
            <p>分配角色
              <el-select v-model="selectedRoleId" placeholder="请选择角色">
                <el-option
                  v-for="item in rolesList"
                  :key="item.id"
                  :label="item.roleName"
                  :value="item.id">
                </el-option>
              </el-select>
            </p>
          </div>
          <span slot="footer" class="dialog-footer">
            <el-button @click="showSetRoleVisible = false">取 消</el-button>
            <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
          </span>
        </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  data () {
    // 验证邮箱的规则
    var checkEmail = (rule, value, callback) => {
      const regEmail = /^\w+@\w+(\.\w+)+$/
      if (regEmail.test(value)) {
        return callback()
      } else {
        callback(new Error('请输入合法邮箱地址'))
      }
    }
    // 验证手机号的规则
    var checkMobile = (rule, value, callback) => {
      const regMobile = /^1[34578]\d{9}$/
      if (regMobile.test(value)) {
        return callback()
      } else {
        callback(new Error('请输入合法手机号'))
      }
    }

    return {
      // 获取用户例表的参数对象
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 5
      },
      userList: [],
      total: 0,
      addDialogVisible: false,
      showEditDialogVisible: false,
      //  添加用户的表单数据
      addUserForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      AddUserRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      userInfo: {},
      showSetRoleVisible: false,
      setUserInfo: {},
      rolesList: [],
      // 已选中的角色id
      selectedRoleId: ''
    }
  },
  created () {
    this.getUserList()
  },
  methods: {
    async getUserList () {
      const res = await this.$http.get('users', { params: this.queryInfo })
      if (res.data.meta.status !== 200) {
        this.$message.err(res.data.meta.msg)
      } else {
        this.userList = res.data.data.users
        this.total = res.data.data.total
        console.log(this.userList)
      }
    },
    handleSizeChange (newSize) {
      this.queryInfo.pagesize = newSize
      this.getUserList()
    },
    handleCurrentChange (newPage) {
      this.queryInfo.pagenum = newPage
      this.getUserList()
    },
    async userStateChange (userinfo) {
      const res = await this.$http.put(`users/${userinfo.id}/state/${userinfo.mg_state}`)
      if (res.data.meta.status !== 200) {
        userinfo.mg_state = !userinfo.mg_state
        this.$message.error('数据更新失败')
      } else {
        this.$message.success('数据更新成功')
      }
    },
    //  用户对话框关闭事件
    addDialogClosed () {
      this.$refs.AddUsersFormRef.resetFields()
    },
    // 点击按钮，添加用户
    addUser () {
      this.$refs.AddUsersFormRef.validate(async (valid) => {
        if (!valid) return false
        // 可以发起添加用户的网络请求
        const res = await this.$http.post('users', this.addUserForm)
        if (res.data.meta.status !== 201) {
          this.$message.error('添加用户失败')
        } else {
          this.$message.success('添加用户成功')
          this.addDialogVisible = false
          this.getUserList()
        }
      })
    },
    // 修改用户对话框
    async showEditDialog (id) {
      this.showEditDialogVisible = true
      const res = await this.$http.get('users/' + id)
      if (res.data.meta.status !== 200) {
        this.$message.error('获取信息失败')
      } else {
        this.userInfo = res.data.data
      }
    },
    // 关闭修改对话框事件
    editDialogClosed () {
      this.$refs.EidtUsersFormRef.resetFields()
    },
    // 点击确定。修改用户信息
    editUser () {
      this.$refs.EidtUsersFormRef.validate(async (valid) => {
        if (!valid) return false
        // 发起修改用户信息请求
        const res = await this.$http.put('users/' + this.userInfo.id, {
          email: this.userInfo.email,
          mobile: this.userInfo.mobile
        })
        if (res.data.meta.status !== 200) {
          this.$message.error('更新用户信息失败')
        } else {
          this.$message.success('更新用户信息成功')
          this.showEditDialogVisible = false
          this.getUserList()
        }
      })
    },
    // 删除用户
    deletInfo (id) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const res = await this.$http.delete('users/' + id)
        if (res.data.meta.status !== 200) {
          this.$message.error('删除失败')
        } else {
          this.$message.success('删除成功')
          this.getUserList()
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 打开分配角色对话框
    async showSetRole (setUserInfo) {
      this.setUserInfo = setUserInfo
      const res = await this.$http.get('roles')
      if (res.data.meta.status !== 200) {
        this.$message.error('获取角色数据失败')
      } else {
        this.rolesList = res.data.data
      }
      this.showSetRoleVisible = true
    },
    // 关闭分配角色对话框
    setRoleDialogClosed () {
      this.selectedRoleId = ''
      this.setUserInfo = ''
    },
    // 为用户分配角色
    async saveRoleInfo () {
      if (!this.selectedRoleId) {
        this.$message.error('请选择要分配的角色')
      } else {
        const res = await this.$http.put(`users/${this.setUserInfo.id}/role`, { rid: this.selectedRoleId })
        if (res.data.meta.status !== 200) {
          this.$message.error('分配角色失败')
        } else {
          this.showSetRoleVisible = false
          this.$message.success('角色分配成功')
          this.getUserList()
        }
      }
    }
  }

}
</script>

<style lang="less" scoped>
</style>
